// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import { WinBase } from "../../../script/wins/WinBase";
import { game } from "../../game/control/game";
import { ccs } from "../../util/services";
import config, { matchCode } from "../config";
import global from "../global";
import * as Util from "../util";
const {ccclass, property} = cc._decorator;
export enum matchType {
    "random",
    "rank",
}

@ccclass
export default class NewClass extends WinBase {

    timer = null;
    state = {
        match: 0,
        room: 0
    }
    matchMode: number = matchType.random;
    start () {
        this.setRankInfo();
        this.touchEndEventScale(this.nodes.matchBtn, () => {this.matchPlayers()});
        this.touchEndEventScale(this.nodes.rankBtn, () => {this.matchPlayers(matchCode.rankCode)});
        this.initSDK();
        this.registerEvent('upRank', this.setRankInfo)
    }
    setRankInfo() {
        let rank = game.playerMgr.heroInfo.rank;
        //查看当前的金钱
        this.nodes.rankName.getComponent(cc.Label).string = "当前段位：" + ccs.dataMgr.getRankById(rank.id).name;
        this.nodes.rankMoney.getComponent(cc.Label).string = "个人财富：" + ccs.gf.getOmitNum(game.playerMgr.heroInfo.money);
        for(let i = 0; i < 3; i++) {
            ccs.spriteExd.setSprite(this.nodes.star.children[i], ccs.resMgr.getRankIcon(i < rank.star?'star1': "star0"));
        }
    }
    onDisable() {
        if(this.state.match) {
            clearInterval(this.timer);
            global.room.cancelPlayerMatch({matchType: MGOBE.ENUM.MatchType.PLAYER_COMPLEX});
        }
    }
    // SDK 初始化
    initSDK() {
        if (Util.isInited()) {
            return //Util.appendLog("SDK 已经初始化，无需重复操作");
        }

        // Util.appendLog("正在初始化 SDK");
        // 隐藏状态 1，正常状态，2 迷雾状态  3, 埋伏 
        Util.initSDK(event => {
            if (event.code === MGOBE.ErrCode.EC_OK) {
                // Util.appendLog("初始化 SDK 成功");
                // this.initView();
                // global.room.onUpdate = () => this.onRoomUpdate();
            } else {
                Util.appendLog(`网络连接失败`);
                // Util.appendLog(`初始化 SDK 失败，错误码：${event.code}`);
            }
        });
    }
    //匹配对战
    // SDK 随机匹配
    matchPlayers(matchCode?: string) {
        this.matchMode = matchType.random;
        if(matchCode) {
            this.matchMode = matchType.rank;
            //排位匹配
            let date = new Date().getHours();
            if(date < 18 || date > 22) {
                return ccs.winMgr.showWin("toast", {msg: "未到开放时间"});
            }
        }
        if(!global.room) {
            this.initSDK();
            return;
        }
        if (!matchCode) {
            matchCode = config.matchCode;
        }
        
        this.toggleBtn(false);
        if(this.state.match) return;
        this.state.match = 1;
        this.timer = setInterval(() => Util.appendLog(`正在匹配，请稍等。`), 1000);
        Util.appendLog(`正在匹配。请稍等，默认超时时间为 12 秒。`);

        // 注意：这里没有使用匹配属性，如果匹配规则中有设置匹配属性，这里需要做调整
        const matchAttributes: MGOBE.types.MatchAttribute[] = [];
        if(matchCode) {
            
            matchAttributes.push({
                name: "rank",
                value: game.playerMgr.heroInfo.rank.id
            });
        }

        const playerInfo: MGOBE.types.MatchPlayerInfoPara = {
            name: game.playerMgr.heroInfo.name,
            customPlayerStatus: game.playerMgr.heroInfo.money,
            customProfile: "",
            matchAttributes,
        };

        const matchPlayersPara: MGOBE.types.MatchPlayersPara = {
            matchCode,
            playerInfo,
        };

        global.room.initRoom();
        global.room.matchPlayers(matchPlayersPara, event => {
            clearInterval(this.timer);
            if (event.code === MGOBE.ErrCode.EC_OK) {
                Util.appendLog(`匹配成功，房间ID：${event.data.roomInfo.id}`);
                ccs.winMgr.showWin("popPkWin", {matchMode: this.matchMode});
                this.state.match = 0;
            } else {
                Util.appendLog(`匹配失败，错误码：${event.code}`);
            }
            this.toggleBtn(true);
        });
    }
    toggleBtn(show: boolean) {
        if(this.matchMode === matchType.random) {
            this.nodes.matchBtn.active = show;
            this.nodes.matchWait.active = !show;
        } else {
            this.nodes.rankBtn.active = show;
            this.nodes.rankWait.active = !show;
        }
    }
    // update (dt) {}
}
